<template>
  <div class="photo-view" :class="viewModeClass">
    <!-- 工具栏 -->
    <div class="photo-toolbar">
      <div class="toolbar-left">
        <el-button-group>
          <el-button 
            :type="viewMode === 'grid' ? 'primary' : ''"
            @click="setViewMode('grid')"
            size="small"
          >
            <el-icon><Grid /></el-icon>
          </el-button>
          <el-button 
            :type="viewMode === 'list' ? 'primary' : ''"
            @click="setViewMode('list')"
            size="small"
          >
            <el-icon><List /></el-icon>
          </el-button>
        </el-button-group>
        
        <el-select
          v-model="sortBy"
          @change="handleSortChange"
          size="small"
          style="width: 150px; margin-left: 12px;"
        >
          <el-option label="拍摄时间" value="capturedAt" />
          <el-option label="创建时间" value="createdAt" />
          <el-option label="文件名" value="fileName" />
          <el-option label="文件大小" value="fileSize" />
        </el-select>
        
        <el-button 
          @click="toggleSortOrder"
          size="small"
          style="margin-left: 8px;"
        >
          <el-icon>
            <Sort v-if="sortOrder === 'asc'" />
            <Sort v-else />
          </el-icon>
        </el-button>
      </div>
      
      <div class="toolbar-right">
        <el-checkbox
          v-model="selectMode"
          @change="handleSelectModeChange"
          style="margin-right: 12px;"
        >
          选择模式
        </el-checkbox>
        
        <el-dropdown trigger="click" @command="handleBatchCommand" v-if="selectedPhotos.length > 0">
          <el-button size="small">
            批量操作
            <el-icon class="el-icon--right"><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="addToAlbum">
                <el-icon><FolderAdd /></el-icon>
                添加到相册
              </el-dropdown-item>
              <el-dropdown-item command="addTags">
                <el-icon><CollectionTag /></el-icon>
                添加标签
              </el-dropdown-item>
              <el-dropdown-item command="setRating">
                <el-icon><Star /></el-icon>
                设置评分
              </el-dropdown-item>
              <el-dropdown-item command="delete" divided>
                <el-icon><Delete /></el-icon>
                删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    
    <!-- 照片网格视图 -->
    <div v-if="viewMode === 'grid'" class="photo-grid-container">
      <div class="photo-grid" :style="gridStyle">
        <PhotoCard
          v-for="photo in photos"
          :key="photo.id"
          :photo="photo"
          :selectable="selectMode"
          :selected="selectedPhotos.some(p => p.id === photo.id)"
          @click="handlePhotoClick"
          @contextmenu="handleContextMenu"
          @select="handlePhotoSelect"
          @favorite="handlePhotoFavorite"
        />
      </div>
      
      <!-- 加载更多 -->
      <div v-if="hasMore" class="load-more">
        <el-button @click="loadMore" :loading="loading">
          加载更多
        </el-button>
      </div>
      
      <!-- 空状态 -->
      <div v-if="!loading && photos.length === 0" class="empty-state">
        <el-empty description="暂无照片" />
      </div>
    </div>
    
    <!-- 照片列表视图 -->
    <div v-else class="photo-list-container">
      <el-table
        :data="photos"
        @selection-change="handleSelectionChange"
        @row-click="handleRowClick"
        @row-contextmenu="handleRowContextMenu"
        style="width: 100%"
      >
        <el-table-column
          v-if="selectMode"
          type="selection"
          width="55"
        />
        
        <el-table-column label="缩略图" width="100">
          <template #default="{ row }">
            <div class="list-thumbnail">
              <img
                :src="getThumbnailUrl(row)"
                :alt="row.fileName"
                @error="handleImageError"
              />
            </div>
          </template>
        </el-table-column>
        
        <el-table-column
          prop="fileName"
          label="文件名"
          min-width="200"
          show-overflow-tooltip
        />
        
        <el-table-column
          prop="capturedAt"
          label="拍摄时间"
          width="180"
          sortable
        >
          <template #default="{ row }">
            {{ formatDate(row.capturedAt || row.createdAt) }}
          </template>
        </el-table-column>
        
        <el-table-column
          prop="fileSize"
          label="文件大小"
          width="120"
          sortable
        >
          <template #default="{ row }">
            {{ formatFileSize(row.fileSize) }}
          </template>
        </el-table-column>
        
        <el-table-column
          label="尺寸"
          width="120"
        >
          <template #default="{ row }">
            {{ row.width && row.height ? `${row.width}×${row.height}` : '未知' }}
          </template>
        </el-table-column>
        
        <el-table-column
          prop="cameraModel"
          label="相机型号"
          width="150"
          show-overflow-tooltip
        />
        
        <el-table-column
          label="评分"
          width="100"
        >
          <template #default="{ row }">
            <el-rate
              v-model="row.rating"
              :max="5"
              size="small"
              @change="handleRatingChange(row, $event)"
            />
          </template>
        </el-table-column>
        
        <el-table-column
          label="操作"
          width="120"
          fixed="right"
        >
          <template #default="{ row }">
            <el-button
              type="text"
              size="small"
              @click.stop="openPhotoDetail(row)"
            >
              详情
            </el-button>
            <el-dropdown trigger="click" @command="(command) => handleRowCommand(command, row)">
              <el-button type="text" size="small">
                更多
                <el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="openInFolder">
                    <el-icon><FolderOpened /></el-icon>
                    在文件夹中显示
                  </el-dropdown-item>
                  <el-dropdown-item command="openWithDefaultApp">
                    <el-icon><View /></el-icon>
                    使用默认应用打开
                  </el-dropdown-item>
                  <el-dropdown-item command="addToAlbum">
                    <el-icon><FolderAdd /></el-icon>
                    添加到相册
                  </el-dropdown-item>
                  <el-dropdown-item command="addTags">
                    <el-icon><CollectionTag /></el-icon>
                    添加标签
                  </el-dropdown-item>
                  <el-dropdown-item command="delete" divided>
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[20, 50, 100, 200]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 批量操作对话框 -->
    <el-dialog
      v-model="batchDialogVisible"
      :title="batchDialogTitle"
      width="500px"
    >
      <component
        :is="batchDialogComponent"
        v-if="batchDialogComponent"
        :photos="selectedPhotos"
        @confirm="handleBatchConfirm"
        @cancel="batchDialogVisible = false"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElButton, ElButtonGroup, ElIcon, ElSelect, ElOption, ElCheckbox, ElDropdown, ElDropdownMenu, ElDropdownItem, ElTable, ElTableColumn, ElRate, ElPagination, ElDialog, ElEmpty, ElMessage } from 'element-plus';
import { Grid, List, Sort, ArrowDown, FolderAdd, CollectionTag, Star, Delete, FolderOpened, View } from '@element-plus/icons-vue';
import type { Photo } from '../../types/photo';
import { useAppStore } from '../../stores/app';
import PhotoCard from './PhotoCard.vue';

// 导入全局类型
import '../../types/global'

interface Props {
  photos: Photo[];
  loading?: boolean;
  hasMore?: boolean;
  total?: number;
  currentPage?: number;
  pageSize?: number;
}

interface Emits {
  (e: 'load-more'): void;
  (e: 'page-change', page: number): void;
  (e: 'size-change', size: number): void;
  (e: 'sort-change', sortBy: string, sortOrder: 'asc' | 'desc'): void;
  (e: 'photo-click', photo: Photo): void;
  (e: 'photo-contextmenu', photo: Photo, event: MouseEvent): void;
  (e: 'photo-select', photo: Photo, selected: boolean): void;
  (e: 'photo-favorite', photo: Photo): void;
  (e: 'photo-rating-change', photo: Photo, rating: number): void;
  (e: 'batch-operation', operation: string, photos: Photo[], data?: any): void;
}

const props = withDefaults(defineProps<Props>(), {
  loading: false,
  hasMore: false,
  total: 0,
  currentPage: 1,
  pageSize: 50
});

const emit = defineEmits<Emits>();

const router = useRouter();
const appStore = useAppStore();

// 视图模式
const viewMode = computed(() => appStore.photoViewMode);
const viewModeClass = computed(() => `photo-view--${viewMode.value}`);

// 排序
const sortBy = ref('captured_at');
const sortOrder = ref<'asc' | 'desc'>('desc');

// 选择模式
const selectMode = ref(false);
const selectedPhotos = ref<Photo[]>([]);

// 批量操作对话框
const batchDialogVisible = ref(false);
const batchDialogTitle = ref('');
const batchDialogComponent = ref<any>(null);

// 网格样式
const gridStyle = computed(() => {
  const columns = appStore.gridColumns;
  return {
    display: 'grid',
    gridTemplateColumns: `repeat(${columns}, 1fr)`,
    gap: '16px'
  };
});

// 设置视图模式
const setViewMode = (mode: 'grid' | 'list') => {
  appStore.setPhotoViewMode(mode);
};

// 处理排序变更
const handleSortChange = () => {
  emit('sort-change', sortBy.value, sortOrder.value);
};

// 切换排序顺序
const toggleSortOrder = () => {
  sortOrder.value = sortOrder.value === 'asc' ? 'desc' : 'asc';
  handleSortChange();
};

// 处理选择模式变更
const handleSelectModeChange = (enabled: boolean) => {
  if (!enabled) {
    selectedPhotos.value = [];
  }
};

// 处理照片点击
const handlePhotoClick = (photo: Photo) => {
  if (selectMode.value) {
    handlePhotoSelect(photo, !selectedPhotos.value.some(p => p.id === photo.id));
  } else {
    emit('photo-click', photo);
  }
};

// 处理照片右键菜单
const handleContextMenu = (photo: Photo, event: MouseEvent) => {
  event.preventDefault();
  emit('photo-contextmenu', photo, event);
};

// 处理照片选择
const handlePhotoSelect = (photo: Photo, selected: boolean) => {
  if (selected) {
    selectedPhotos.value.push(photo);
  } else {
    selectedPhotos.value = selectedPhotos.value.filter(p => p.id !== photo.id);
  }
  emit('photo-select', photo, selected);
};

// 处理照片收藏
const handlePhotoFavorite = (photo: Photo) => {
  emit('photo-favorite', photo);
};

// 处理评分变更
const handleRatingChange = (photo: Photo, rating: number) => {
  emit('photo-rating-change', photo, rating);
};

// 处理表格选择变更
const handleSelectionChange = (selection: Photo[]) => {
  selectedPhotos.value = selection;
};

// 处理行点击
const handleRowClick = (row: Photo) => {
  emit('photo-click', row);
};

// 处理行右键菜单
const handleRowContextMenu = (row: Photo, column: any, event: MouseEvent) => {
  event.preventDefault();
  emit('photo-contextmenu', row, event);
};

// 处理行命令
const handleRowCommand = (command: string, row: Photo) => {
  switch (command) {
    case 'openInFolder':
      // 打开文件夹
      break;
    case 'openWithDefaultApp':
      // 使用默认应用打开
      break;
    case 'addToAlbum':
      // 添加到相册
      break;
    case 'addTags':
      // 添加标签
      break;
    case 'delete':
      // 删除照片
      break;
  }
};

/**
 * 处理批量操作命令
 * @param command 操作命令
 */
const handleBatchCommand = (command: string) => {
  if (selectedPhotos.value.length === 0) {
    ElMessage.warning('请先选择照片');
    return;
  }

  switch (command) {
    case 'addToAlbum':
      batchDialogTitle.value = '添加到相册';
      // batchDialogComponent.value = 'BatchAddToAlbum';
      break;
    case 'addTags':
      batchDialogTitle.value = '添加标签';
      // batchDialogComponent.value = 'BatchAddTags';
      break;
    case 'setRating':
      batchDialogTitle.value = '设置评分';
      // batchDialogComponent.value = 'BatchSetRating';
      break;
    case 'delete':
      // 直接执行删除操作
      emit('batch-operation', 'delete', selectedPhotos.value);
      return;
  }

  batchDialogVisible.value = true;
};

/**
 * 处理批量操作确认
 * @param data 操作数据
 */
const handleBatchConfirm = (data: any) => {
  // 根据操作类型确定操作名称
  let operation = '';
  switch (batchDialogTitle.value) {
    case '添加到相册':
      operation = 'addToAlbum';
      break;
    case '添加标签':
      operation = 'addTags';
      break;
    case '设置评分':
      operation = 'setRating';
      break;
    default:
      operation = batchDialogTitle.value;
  }
  
  emit('batch-operation', operation, selectedPhotos.value, data);
  batchDialogVisible.value = false;
};

/**
 * 加载更多照片
 */
const loadMore = () => {
  emit('load-more');
};

/**
 * 处理页码变更
 * @param page 页码
 */
const handleCurrentChange = (page: number) => {
  emit('page-change', page);
};

/**
 * 处理每页数量变更
 * @param size 每页数量
 */
const handleSizeChange = (size: number) => {
  emit('size-change', size);
};

/**
 * 打开照片详情
 * @param photo 照片对象
 */
const openPhotoDetail = (photo: Photo) => {
  router.push(`/photo/${photo.id}`);
};

/**
 * 获取缩略图URL
 * @param photo 照片对象
 * @returns 缩略图URL
 */
const getThumbnailUrl = (photo: Photo) => {
  if (photo.thumbnail_path) {
    return `file://${photo.thumbnail_path}`;
  }
  return `file://${photo.file_path}`;
};

/**
 * 处理图片加载错误
 * @param event 错误事件
 */
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement;
  // 设置默认图片或错误处理
  img.src = '/path/to/default/image.jpg';
};

/**
 * 格式化日期
 * @param dateString 日期字符串
 * @returns 格式化后的日期字符串
 */
const formatDate = (dateString: string) => {
  if (!dateString) return '未知';
  const date = new Date(dateString);
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  });
};

/**
 * 格式化文件大小
 * @param bytes 文件大小（字节）
 * @returns 格式化后的文件大小字符串
 */
const formatFileSize = (bytes: number) => {
  if (!bytes) return '未知';
  
  const units = ['B', 'KB', 'MB', 'GB'];
  let size = bytes;
  let unitIndex = 0;
  
  while (size >= 1024 && unitIndex < units.length - 1) {
    size /= 1024;
    unitIndex++;
  }
  
  return `${size.toFixed(1)} ${units[unitIndex]}`;
};
</script>

<style scoped lang="scss">
.photo-view {
  display: flex;
  flex-direction: column;
  height: 100%;
  
  .photo-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 16px;
    border-bottom: 1px solid var(--el-border-color-light);
    
    .toolbar-left {
      display: flex;
      align-items: center;
    }
    
    .toolbar-right {
      display: flex;
      align-items: center;
    }
  }
  
  .photo-grid-container {
    flex: 1;
    overflow-y: auto;
    padding: 16px;
    
    .photo-grid {
      width: 100%;
    }
    
    .load-more {
      display: flex;
      justify-content: center;
      margin-top: 20px;
    }
    
    .empty-state {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 300px;
    }
  }
  
  .photo-list-container {
    flex: 1;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    
    .el-table {
      flex: 1;
    }
    
    .list-thumbnail {
      width: 60px;
      height: 60px;
      border-radius: 4px;
      overflow: hidden;
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }
    
    .pagination-container {
      padding: 16px;
      display: flex;
      justify-content: center;
      border-top: 1px solid var(--el-border-color-light);
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .photo-view {
    .photo-toolbar {
      flex-direction: column;
      gap: 12px;
      align-items: stretch;
      
      .toolbar-left,
      .toolbar-right {
        justify-content: center;
      }
    }
    
    .photo-grid-container {
      padding: 8px;
    }
  }
}
</style>